package com.itjeffrey.autocode.util;

import com.itjeffrey.autocode.constant.SysConstant;
import com.itjeffrey.autocode.runner.TemplateInitRunner;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.freemarker.FreeMarkerTemplateUtils;

import java.io.*;
import java.util.Map;

/**
 * 模板工具类
 *
 * @From: Jeffrey
 * @Date: 2020/11/15
 */
@Slf4j
public class TemplateUtil {

    /**
     * 根据模板名称获取自定义格式的字符串模板
     *
     * @param modelName 模板名【eg：entity】
     * @return
     */
    public static String fileToStr(String modelName) {
        log.trace("-->Initializing " + modelName + " Template START...");
        StringBuffer buffer = new StringBuffer();
        try {
            BufferedReader br = new BufferedReader(new FileReader(System.getProperty(SysConstant.USER_DIR) +
                    SysConstant.MODEL_ABSTRACT_PATH + modelName + SysConstant.FTL_SUFFIX));
            String line;
            while ((line = br.readLine()) != null) {
                log.trace(line);
                int i = 0;
                if (line.startsWith(" ") && line.length() > 1) {
                    while (line.charAt(i) == 32) { //空格
                        buffer.append("&nbsp;");
                        i++;
                    }
                    buffer.append(line.substring(i)).append("<br/>");
                } else {
                    buffer.append(line).append("<br/>");
                }
//                buffer.append(line).append(System.getProperty("line.separator"));// 保持原有换行格式
            }
            log.trace("<--Initializing " + modelName + " Template END!");
            br.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buffer.toString();
    }

    /**
     * 根据自定义格式的字符串模板和模板数据输出代码
     *
     * @param modelName 模板名 如：entity
     * @param modelMap  模板数据
     * @return
     */
    public static String outputModelData(String modelName, Map<String, Object> modelMap) {
        StringWriter stringWriter = null;
        try {
            //获取freeMarker的配置类
            Configuration config = SpringContextHolder.getBean(Configuration.class);
            //字符串模板加载器
            StringTemplateLoader stringTemplateLoader = new StringTemplateLoader();
            //根据模板名称获取自定义格式的字符串模板
            TemplateInitRunner runner = SpringContextHolder.getBean(TemplateInitRunner.class);
            String strModel = runner.getTemplateMap().get(modelName); //优化 模板工具类加载时就读取出模板数据
            //向字符串模板加载器中加入字符串模板
            stringTemplateLoader.putTemplate(modelName, strModel);
            //将字符串模板加载器set到config
            config.setTemplateLoader(stringTemplateLoader);

            stringWriter = new StringWriter();
            //通过config配置类获取指定模板名称的模板对象
            Template template = config.getTemplate(modelName, SysConstant.CHARSET_UTF8);
            Writer out = new BufferedWriter(stringWriter);
            //执行
            template.process(modelMap, out);
            //释放连接
            out.flush();
            out.close();
        } catch (TemplateException | IOException e) {
            e.printStackTrace();
        }
        return stringWriter.toString();
    }

    /**
     * 根据模板和数据生成文本
     *
     * @param modelName
     * @param modelMap
     * @return
     */
    public static String parseTemplateAndModel(String modelName, Map<String, Object> modelMap) {
        //导入freemarker模板中的Configuration包
        Configuration cfg = SpringContextHolder.getBean(Configuration.class);
        String html = null;
        Template t;
        try {
            t = cfg.getTemplate(modelName + SysConstant.MODEL_FILE_SUFFIX);
            html = FreeMarkerTemplateUtils.processTemplateIntoString(t, modelMap);
        } catch (IOException | TemplateException e) {
            e.printStackTrace();
        }
        return html;
    }
}
